package com.tengits.mqttmonitor.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


public class Utils {
    public static final String PASSWORD_FILE = "pwd.conf";
    public static final String BROKER_CONFIG_FILE = "mqtt.properties";

    public static void isPortOpen(int port) {
        SocketCheckTask task = new SocketCheckTask();
        task.execute(port);
    }

    public static String  getVersion() {
        String javaVersion = System.getProperty("java.version");
        System.out.format("Java Version = '%s'", javaVersion);
        return javaVersion;
    }

    public static String getDefaultIpAddresses(Context mContext) {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        //LinkProperties prop = cm.getActiveLinkProperties();
        LinkProperties prop = null;
        String addres = null;
        try {
            prop = (LinkProperties) cm.getClass().getMethod("getActiveLinkProperties").invoke(cm);
            addres = formatIpAddresses(prop);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return addres;
    }

    private static String formatIpAddresses(LinkProperties prop) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        if (prop == null) return null;
        //Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
        List<InetAddress> addressesList = (List<InetAddress>) prop.getClass().getMethod("getAllAddresses").invoke(prop);
        Iterator<InetAddress> iter = addressesList.iterator();
        // If there are no entries, return null
        if (!iter.hasNext()) return null;
        // Concatenate all available addresses, comma separated
        String addresses = "";
        while (iter.hasNext()) {
            InetAddress inetAddress = iter.next();
            //过滤 ipv6 的地址
            if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                addresses = inetAddress.getHostAddress();
                break;
            }
            //addresses += iter.next().getHostAddress();
            //if (iter.hasNext()) addresses += "\n";
        }
        return addresses;
    }

    public static String getBrokerURL(Context ctx) {
        //return Formatter.formatIpAddress(((WifiManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE)).getConnectionInfo().getIpAddress());
//        try {
//             String ipv4;
//             ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
//             for (NetworkInterface ni: nilist)
//                 {
//                     ArrayList<Inet4Address> ialist = Collections.list(ni.getInetAddresses());
//                     for (Inet4Address address: ialist){
//                             if (!address.isLoopbackAddress() && !address.isLinkLocalAddress())
//                                 {
//                                     ipv4=address.getHostAddress();
//                                     return ipv4;
//                                 }
//                         }
//
//                 }
//
//         } catch (SocketException ex) {
//             Log.e("localip", ex.toString());
//         }
//        return "";
        return getDefaultIpAddresses(ctx);
    }

    public static void showDialog(Context content, String message) {
        new AlertDialog.Builder(content).setTitle("Error")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    public static String getSHA(String input) throws NoSuchAlgorithmException {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] messageDigest = md.digest(input.getBytes());

            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw e;
        }
    }

    /**
     * 判断网络是否连接
     */
    private boolean isConnectNormal(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            return true;
        } else {
            /*没有可用网络的时候，延迟3秒再尝试重连*/
            return false;
        }
    }
}

class SocketCheckTask extends AsyncTask<Integer, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Integer... params) {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(InetAddress.getLocalHost().getHostName(), params[0]), 1000);
            socket.close();
            return true;
        } catch (ConnectException ce) {
            ce.printStackTrace();
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean isOpen) {
        Log.i("Async", String.valueOf(isOpen));
    }
}